from django.http import HttpResponseRedirect, HttpResponseServerError
from pagemagic.utils.openid.core import openid_auth_request, OpenidError,\
    openid_auth_handle_response, standartize_openid_url
from pagemagic.decorators import render_to
from django.utils.translation import ugettext
from pagemagic.utils.openid.models import OpenidUser

SESSION_OPENID_USER_VARNAME = 'pagemagic_openid_user_id'
SESSION_OPENID_AUTH_WAITING_VARNAME = 'pagemagic_openid_auth_waiting'

@render_to('pagemagic/openid_error.html', response_class=HttpResponseServerError)
def openid_login(request):
    # step 2: handle response
    if SESSION_OPENID_AUTH_WAITING_VARNAME in request.session:
        (openid_url, next) = request.session.pop(SESSION_OPENID_AUTH_WAITING_VARNAME)
        response = openid_auth_request(request, openid_url)
        auth = openid_auth_handle_response(request, next)
        statuses = {
            'failure': ugettext('Autentification failure'),
            'setup_needed': ugettext('SETUP_NEEDED'),
            'cancel': ugettext('Autentification canceled'),
        }
        if auth.status != 'success':
            return {
                'msg': '%s: %s' % (
                    statuses.get(auth.status, auth.status),
                    auth.message,
                ),
            }

        user, created = OpenidUser.objects.get_or_create(url=standartize_openid_url(openid_url)) #@UnusedVariable
        request.openid_user = user
        request.session[SESSION_OPENID_USER_VARNAME] = user.pk
        request.session.save()

        return response

    # step 1: auth request
    (openid_url, next) = request.GET.get('openid_url', ''), request.GET.get('next')
    if not openid_url:
        return {'msg': '`url` parameter required'}

    try:
        response = openid_auth_request(request, openid_url, next)
        request.session[SESSION_OPENID_AUTH_WAITING_VARNAME] = (openid_url, next)
        return response
    except OpenidError, e:
        return {'msg': e}


#@render_to('pagemagic/openid_error.html', )
def openid_logout(request):
    del request.session[SESSION_OPENID_USER_VARNAME]
    request.session.save()
    return HttpResponseRedirect(request.GET.get('next', '/'))
